var id;
var userName;
var userRole;
var organizationName;
var organizationId;
var totalCount;
var typeCode;
var typeName;
var typeCount;
$(function () {
    // $("#scan").hide();
    init();
    //加载用户信息
    selectUserInformation();
    indexIs();
    loadWxConfig();
})


function init() {
    FastClick.attach(document.body);
    loadCookie();
    $("[target]").on("click", function (e) {
        var target = $(e.target);
        if (target.attr("target") == null) {
            target = target.parents("[target]");
        }
        window.location.href = "/" + target.attr("target");
    })

    $("#blockB").on("click", function (e) {
        $.alert("暂未开放");
    })

    $("#productBox").on("click", function () {
        window.location.href = "/plist/#";
    })
    $("#equipmentSearch").on("click", function () {
        window.location.href = "/search/#";
    })
    $("#headImg").on("click", function () {
        window.location.href = "/userInfo/#";
    })
    $("#info").on("click", function (e) {
        if ($(e.target).hasClass("moreLink") || $(e.target).parents(".moreLink").length > 0) {
            return;
        }
        $.confirm("是否要重新认证新的已授权身份？", "切换授权", function () {
            equipmemtService.logOut({}, function (data) {
                if (data.success) {
                    window.location.href = "/login?state=9";
                } else {
                    $.alert(data.errorMsg);
                }
            })
        });
    })
}

function selectUserInformation() {
    equipmemtService.queryPersonInformation({}, function (data) {
        if (data.success) {
            userName = data.data[0].name;
            userRole = data.data[0].cRoleName;
            organizationName = data.data[0].organizationName + data.data[0].organizationNameSon;
            organizationId = data.data[0].organizationId
            $("#name").html(userName);
            $("#job").html(" " + userRole);
            $("#workspace").html(organizationName);
            loadWorkSpace(data.data[0].cRoleId);
        } else {
            $.toptip(data.errorMsg);
        }
    })
}

function loadWorkSpace(roleId) {
    switch (roleId) {
        case "1"://超管
            $("#equipmentSearch").fadeIn();
            $("#workSpanA").fadeIn();
            $("#workSpanB").fadeIn();
            $("#workSpanC").fadeIn();
            // $("#workSpanD").fadeIn();
            $("#workSpanE").fadeIn();
            // $("#workSpanF").fadeIn();
            $("#workMenuA").fadeIn();
            $("#workMenuB").fadeIn();
            $("#workMenuC").fadeIn();
            // $("#workMenuD").fadeIn();
            $("#workMenuE").fadeIn();
            $("#workMenuF").fadeIn();
            $("#workMenuG").fadeIn();


            $("#blockC").fadeIn();
            // $("#blockB").fadeIn();
            $("#blockE").fadeIn();
            break;
        case "2"://设备管理
            $("#equipmentSearch").fadeIn();
            $("#workSpanA").fadeIn();
            // $("#workSpanB").fadeIn();
            $("#workSpanC").fadeIn();
            $("#workSpanD").fadeIn();
            // $("#workSpanE").fadeIn();
            // $("#workSpanF").fadeIn();
            $("#workMenuA").fadeIn();
            $("#workMenuB").fadeIn();
            $("#workMenuC").fadeIn();
            // $("#workMenuD").fadeIn();
            $("#workMenuE").fadeIn();
            $("#workMenuF").fadeIn();
            $("#workMenuG").fadeIn();
            $("#blockC").fadeIn();
            $("#blockE").fadeIn();
            break;
        case "3"://库管
            $("#equipmentSearch").fadeIn();
            // $("#workSpanA").fadeIn();
            $("#workSpanB").fadeIn();
            // $("#workSpanC").fadeIn();
            $("#workSpanD").fadeIn();
            $("#workMenuB").fadeIn();
            $("#workMenuE").fadeIn();
            $("#workMenuF").fadeIn();
            $("#workMenuG").fadeIn();
            $("#blockC").fadeIn();
            $("#analysis1").hide();
            $("#blockE").fadeIn();
            break;
        case "4"://维修
            // $("#workSpanA").fadeIn();
            // $("#workSpanB").fadeIn();
            // $("#workSpanC").fadeIn();
            // $("#workSpanD").fadeIn();
            $("#workSpanE").fadeIn();
            // $("#workMenuA").fadeIn();
            // $("#workMenuB").fadeIn();
            $("#workMenuD").fadeIn();
            break;
        case "5"://用户
            $("#workSpanD").fadeIn();
            $("#workMenuB").fadeIn();
            $("#workMenuA").fadeIn();
        default ://其他
            $("#workSpanD").fadeIn();
            $("#workMenuA").fadeIn();
    }
    $(".titleTip").hide();
    if ($("#workSpanE").is(':visible')) {
        //查询我的维修任务，包括未接受
        equipmemtService.queryMyJob({
            rstate: "'209001','209002'",
            estate: "'201402','201501'"
        }, function (data) {
            if (data.success) {
                var num = data.datas.length;
                $("#workSpanE .num").attr("class", "num").html(num);
            } else {
                $.toptip(data.errorMsg);
            }
        })
        //未接受任务
        equipmemtService.queryMyJob({
            rstate: "'209001'",
            estate: "'201402'"
        }, function (data) {
            if (data.success) {
                var num = data.datas.length;
                if (num > 0) {
                    $("#myJobt").show();
                    $("#myJobt").html(num);
                }
            } else {
                $.toptip(data.errorMsg);
            }
        })
    }
    if ($("#workSpanA").is(':visible')) {
        equipmemtService.queryEquipmentTotal({state: 203002}, function (data) {
            if (data.success) {
                var num = data.datas[0].totalNum;
                $("#workSpanA .num").attr("class", "num").html(num);
            } else {
                $.toptip(data.errorMsg);
            }
        })
    }
    if ($("#workSpanD").is(':visible')) {
        equipmemtService.myMain({
            state: "'201201','201202','201203','201301','201302','201402','201501','201502'"
        }, function (data) {
            if (data.success) {
                var num = data.datas.length;
                if (num > 0) {
                    $("#myMaint").show();
                    $("#myMaint").html(num);
                }
                $("#workSpanD .num").attr("class", "num").html(num);
            } else {
                $.toptip(data.errorMsg);
            }
        })
    }
    if ($("#workSpanC").is(':visible')) {
        equipmemtService.acceptedList({
            state: "'201202','201201'"
        }, function (data) {
            if (data.success) {
                var num = data.datas.length;
                if (num > 0) {
                    $("#myCheckt").show();
                    $("#myCheckt").html(num);
                }
                $("#workSpanC .num").attr("class", "num").html(num);
                $("#workSpanE .num").attr("class", "num").html(num);
            } else {
                $.toptip(data.errorMsg);
            }
        })
    }
    if ($("#workMenuA").is(':visible')) {
        //查询设备总数
        equipmemtService.queryEquipmentTotal({}, function (data) {
            if (data.success) {
                var totalNum = data.datas[0].totalNum;
                totalCount = totalNum;
                if (totalNum != 0) {
                    $("#alllistt").show();
                    $("#alllistt").html(totalNum);
                }
            } else {
                $.toptip(data.errorMsg);
            }
        })
        // equipmemtService.accepted({}, function (data) {
        //     if (data.success) {
        //         var num = data.datas[0].totalNum;
        //         $("#t2").html(" 待处理：" + num + " 台");
        //     } else {
        //         $.toptip(data.errorMsg);
        //     }
        // })
    }
    if ($("#blockC").is(':visible')) {
        equipmemtService.warehouseInfo({
            organization: organizationId
        }, function (data) {
            if (data.success) {
                $(data.datas).each(function (i, warehouse) {
                    // if (warehouse.organizationId == organizationId) {
                    if (true) {
                        var houseBox = $(" <div class=\"flex warehouse\"> <div class=\"title\"><span class=\"fa fa-warehouse\"> " +
                            warehouse.name + "【" + warehouse.position + "】"
                            + "</span></div></div>");
                        $("#blockC .menu").after(houseBox);

                        equipmemtService.warehouseDetailInfo({
                            warehouseId: warehouse.id
                        }, function (data) {
                            if (data.success) {
                                data = data.datas;
                                //排序
                                data.sort(function (a, b) {
                                    return (b.warnCount - b.count) - (a.warnCount - a.count)
                                })
                                $(data).each(function (i, item) {
                                    var ab = "a";
                                    if (item.warnCount - item.count >= 0) {
                                        ab = "b";
                                        var num = $("#workSpanB .num").html();
                                        $("#workSpanB .num").html(++num);
                                    }
                                    if (i >= 4) return;//首页只显示前4个
                                    var percent = item.count / item.warnCount / 5 * 100;
                                    var ring;
                                    if (ab == "a") {
                                        ring = $(
                                            "<div class=\"button\">" +
                                            "                    <div class=\"ring\">" +
                                            "                        <div class=\"left\"><div class=\"leftafter\"></div></div>" +
                                            "                        <div class=\"right\"> <div class=\"rightafter\"></div></div>" +
                                            "                        <div class=\"progress\" ><span class=\"name\">" + item.name + "</span><br/><span class=\"tips\">库存充足</span></div>" +
                                            "                    </div>" +
                                            "                </div>");
                                    } else {
                                        ring = $(
                                            "<div class=\"button\">" +
                                            "                    <div class=\"ring warn\">" +
                                            "                        <div class=\"left\"><div class=\"leftafter\"></div></div>" +
                                            "                        <div class=\"right\"> <div class=\"rightafter\"></div></div>" +
                                            "                        <div class=\"progress\" ><span class=\"name\">" + item.name + "</span><br/><span class=\"tips\">库存不足</span></div>" +
                                            "                    </div>" +
                                            "                </div>");
                                    }
                                    houseBox.append(ring);
                                    resizeRing(ring, percent);
                                    ring.on("click", function () {
                                        equipmemtService.warehouseDetailList({
                                            id: item.id,
                                            warehouseId: warehouse.id
                                        }, function (data) {
                                            if (data.success) {
                                                data = data.datas;
                                                $(".weui-popup__container").remove();
                                                var pop = $("<div class=\"weui-popup__container popup-bottom weui-popup__container--visible\" " +
                                                    "style=\"display: block; height: calc( 100% - 180px )\">" +
                                                    "      <div class=\"weui-popup__overlay\"></div>" +
                                                    "      <div class=\"weui-popup__modal\" style='height:100%'>" +
                                                    "        <div class=\"toolbar\">" +
                                                    "          <div class=\"toolbar-inner\">" +
                                                    "            <a href=\"javascript:;\" class=\"picker-button close-popup\">关闭</a>" +
                                                    "            <h1 class=\"title\">" + warehouse.name + "-" + item.name + "</h1>" +
                                                    "          </div>" +
                                                    "        </div>" +
                                                    "        <div class=\"modal-content\">" +
                                                    "<div class='flex wareDetail'><div style='text-align: left;flex: 1;'><strong>当前库存：</strong></div><div style='text-align: left;flex: 1;'>" + item.count + "</div></div>" +
                                                    "<div class='flex wareDetail'><div style='text-align: left;flex: 1;'><strong>警告库存：</strong></div><div style='text-align: left;flex: 1;'>" + item.warnCount + "</div></div>" +
                                                    "<div class='flex wareDetail'><table border='0' cellpadding='0' cellspacing=\"0\"  width='100%'><thead><td>品牌</td><td>型号</td><td>库存数量</td>" +
                                                    // "<td>报警数量</td>" +
                                                    "</thead></table></div>" +
                                                    "        </div>" +
                                                    "      </div>" +
                                                    "    </div>");
                                                $("body").append(pop);
                                                $(data).each(function (i, item) {
                                                    pop.find("table").append("<tr><td>" + item.brandName + "</td><td>" + item.name + "</td><td>" + item.count + item.unit + "</td>" +
                                                        // "<td>"+item.warnCount+"</td>" +
                                                        "</tr>")
                                                })

                                            } else {
                                                $.toptip(data.errorMsg);
                                            }
                                        })
                                    })
                                })
                            } else {
                                $.toptip(data.errorMsg);
                            }
                        })

                    }
                })

            } else {
                $.toptip(data.errorMsg);
            }
        })
    }
}

function resizeRing(ring, percent) {
    var width = $(".ring").parent().width();
    $(".ring").css("font-size", width / 8.2 + "px");
    console.info(percent);
    if (percent >= 100) {
        ring.find(".leftafter").css('transform', "rotateZ(0deg)");
        ring.find(".rightafter").css('transform', "rotateZ(0deg)");
    } else if (percent > 50) {
        ring.find(".leftafter").css('transform', "rotateZ(0deg)");
        ring.find(".rightafter").css('transform', "rotateZ(" + 180 * (100 - percent) / 100 + "deg)");
    } else {
        ring.find(".leftafter").css('transform', "rotateZ(" + 180 * (50 - percent) / 50 + "deg)");
        ring.find(".rightafter").css('transform', "rotateZ(180deg)");
    }
}

function loadWxConfig() {
    $.ajax({
        url: baseService.baseUrl + "/wechat/signUrl.do?app_id=wx15e86d161a4b2da8&url=" + window.location.href,
        data: "",
        dataType: 'json',
        type: "post",
        async: true,
        success: function (msg) {
            wx.ready(function () {
                wxConfigState = true;
                $("#scan2").show();
                $("#scan2").on("click", function () {
                    scanQRCode();
                })
            });
            wx.error(function (res) {
                console.log(res);
                $.toptip('警告：微信扫码控件启动失败', 'warning');
                $("body").on("dblclick", function () {
                    $.alert(res.errMsg);
                })
            });
            configWx({
                appId: msg.app_id, // 必填，公众号的唯一标识
                timestamp: msg.timestamp, // 必填，生成签名的时间戳
                nonceStr: msg.nonceStr, // 必填，生成签名的随机串
                signature: msg.signature // 必填，签名
            });

        },
        error: function (response) {
            $.toptip(response);
        }
    });
}

function configWx(config) {
    config.debug = false;
    config.jsApiList = ["scanQRCode"];
    wx.config(config);
}

function scanQRCode() {
    wx.scanQRCode({
        needResult: 0, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
        scanType: ["qrCode"], // 可以指定扫二维码qrCode还是一维码, "barCode" ，默认二者都有
        success: function (res) {
        }
    });
}


function indexIs() {
    equipmemtService.indexIs({}, function (data) {
        if (data.success) {
            var serverData = data.datas;
            $(serverData).each(function (index, item) {
                var row = $(' <div class="swiper-slide" style="background-image: url(' + item.picture1 + ')"> ' +
                    '                    <div class="productInfo"> ' +
                    '                        <span>' + item.describe + '</span> ' +
                    '                    </div> ' +
                    '                </div> ');
                $("#product").append(row);
                row.on("click", function () {
                    window.location.href = "/pdetail/" + item.code;
                })
            })

            new Swiper('.swiper-container', {
                    speed: 1000,//播放速度
                    autoHeight: true,
                    loop: true,//是否循环播放
                    setWrapperSize: true,
                    autoplay: 2000,
                    pagination: '.swiper-pagination',//分页
                    effect: 'slide',//动画效果
                }
            );

        } else {
            $.toptip(data.errorMsg);
        }
    })
}

function loadCookie() {
    $("#scan2").after("<div class=\"noInfo\"><span>无更多记录</span></div>");
    equipmemtService.queryEquipmentHis(function (history) {
        for (var code in history) {
            var name = history[code].name.split("-");
            var fullname = "";
            if (name.length > 1)
                fullname = history[code].name.substring(name[0].length + name[1].length + 2);
            else
                fullname = "保密信息";
            var button = $("<div class=\"button\" style='background-image: url(" + history[code].externalPhotos + ")' onclick='window.location.href = \"/edetail/" + code + "\"' value='" + code + "'><span class=\"type\">" + name[0] + "</span><br><span>" + fullname + "</span></div>");
            $("#scan2").after(button);
        }
        // $("#blockA .button").height(($("#blockA .button").width()-10)+"px");
    })
}